package org.opendatakit.sensors.wifi;


import java.util.Set;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;


public class MulticastService extends Service{

	private static final String LOGTAG = "MulticastService";
    
	private final IBinder mBinder = new LocalBinder();
 
	Thread receiverThread;
	
	public void onCreate() {
		super.onCreate();
		Log.e(LOGTAG,"MulticastService onCreate entered");
	}
	
	
	public class LocalBinder extends Binder {
		public MulticastService getService() {
		   return MulticastService.this;
		  }
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.e(LOGTAG,"MulticastService onStart");
		return START_STICKY;
	}
	
	
	public void onDestroy(){
		Log.d(LOGTAG,"on destroyed activity");
		ReceiverThread.discovering.set(false);
		super.onDestroy();
	}
	
	@Override
	 public IBinder onBind(Intent intent) {
		Log.e(LOGTAG,"MulticastService onStart");
		return mBinder;
	 }
	
	
	public void startMulticastThread(String cmd) {
		
		Log.d(LOGTAG, "inside start mlcasthread");
		
		WifiManager wifi = (WifiManager)getSystemService( Context.WIFI_SERVICE );
    	
		if(wifi != null){
    	    WifiManager.MulticastLock lock = wifi.createMulticastLock("Multicast Lock");
    	    lock.acquire();
    	}
		Context c =(Context)this;
		//Context c = ((MulticastService)getApplicationContext());
    	Thread T1 = new Thread(new MulticastThread(cmd,c));
    	android.net.wifi.WifiManager wifiMan = (android.net.wifi.WifiManager) this.getSystemService(
		        Context.WIFI_SERVICE);
		WifiInfo wifiInf = wifiMan.getConnectionInfo();
	    String mac = wifiInf.getMacAddress();
	    receiverThread = new Thread(new ReceiverThread(mac,c));
		T1.start();
		receiverThread.start();
		
	}
	
	public Set<WifiDevice> getDeviceList(){
		
		return null;
		
	}
	
	
	

}
